/**
 * 天气预报android简化系统V1.0(武汉永恒成就信息科技有限公司)
 * author:Hu yunbo
 * Email :yunboh@gmail.com
 * Time:2011年2月17日
 */



package Weather.Test;

import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.weather.View.SingleWeatherInfoView;
import com.android.weather.weather.WeatherCurrentCondition;
import com.android.weather.weather.WeatherForecastCondition;
import com.android.weather.weather.WeatherSet;
import com.android.weather.weather.googleWeatherHandler;

/**
 * android Activity
 * @author Hu yunbo
 *
 */
public class Weather1 extends Activity {
	
	
	
private RelativeLayout layout;
	
	private RelativeLayout layout1;
	private RelativeLayout layout2;
	private RelativeLayout layout3;
	
	private ImageView tab1;
	private ImageView tab2;
	private ImageView tab3;
	
	private ImageView first;
	private int current = 1; // 默认选中第一个，可以动态的改变此参数值
	
	
	private final String DEBUG_TAG = "WeatherForcasterDemo";
	private CheckBox chk_usecelsius = null;
	private static String[] CITY_EN = {"hangzhou","shanghai","beijing","tianjin","chongqing","tangshan","shijiazhuang","dalian","haerbin","haikou","changchun","changsha","chengdu","fuzhou","guangzhou","guiyang","hangzhou","hefei","huhehaote","jinan","kunming","lasa","lanzhou","nanchang","nanning","nanning","qingdao","shenzhen","shenyang","taiyuan","wulumuqi","wuhan","xining","xiamen","xuzhou","yinchuan","zhengzhou"};
	private static String[] CITY_CN = {"杭州","上海","北京","天津","重庆","唐山","石家庄","大连","哈尔滨","海口","长春","长沙","成都","福州","广州","贵阳","杭州","合肥","呼和浩特","济南","昆明","拉萨","兰州","南昌","南京","南宁","青岛","深圳","沈阳","太原","乌鲁木齐","武汉","西安","西宁","厦门","徐州","银川","郑州"};
	
	
	
	/**
	 * onCreate
	 */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		
		

	//	this.chk_usecelsius = (CheckBox) findViewById(R.id.chk_usecelsius);

		Button cmd_submit = (Button) findViewById(R.id.cmd_submit);
		cmd_submit.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
			//	Toast.makeText(WeatherForecastDemo.this, "aaa", Toast.LENGTH_LONG).show();
				URL url;
				try {
					/* 获得输入值. */
					String cityParamString = ((EditText) findViewById(R.id.edit_input))
							.getText().toString();
					/* 对输入是汉字的处理*/
					boolean isCharater = isCN(cityParamString);
					int position = 0;
					if(isCharater)
					{
						position = getCnPosition(CITY_CN,cityParamString);
						if(position != -1)
						{
							cityParamString =  CITY_EN[position];
						}
					}
									
					/* 通过参数形式获取天气情况*/
					String queryString = "http://www.google.com/ig/api?weather="
							+ cityParamString;
				
					url = new URL(queryString.replace(" ", "%20"));

				
					SAXParserFactory spf = SAXParserFactory.newInstance();
					SAXParser sp = spf.newSAXParser();

				
					XMLReader xr = sp.getXMLReader();

					googleWeatherHandler gwh = new googleWeatherHandler();
					xr.setContentHandler(gwh);

					xr.parse(new InputSource(url.openStream()));
					WeatherSet ws = gwh.getWeatherSet();

					updateWeatherInfoView(R.id.weather_today, ws
							.getWeatherCurrentCondition());

					updateWeatherInfoView(R.id.weather_1, ws
							.getWeatherForecastConditions().get(0));
					updateWeatherInfoView(R.id.weather_2, ws
							.getWeatherForecastConditions().get(1));
					updateWeatherInfoView(R.id.weather_3, ws
							.getWeatherForecastConditions().get(2));
					updateWeatherInfoView(R.id.weather_4, ws
							.getWeatherForecastConditions().get(3));

				} catch (Exception e) {
					resetWeatherInfoViews();
					Log.e(DEBUG_TAG, "WeatherQueryError", e);
				}
			}
		});
		
		initUI();
	}
	
	/**
	 * 更新天气信息
	 * @param 系统资源ID
	 * @param  天气状态
	 * @throws 抛出MalformedURLException异常
	 */
	private void updateWeatherInfoView(int aResourceID,
			WeatherForecastCondition aWFIS) throws MalformedURLException {
		
		URL imgURL = new URL("http://www.google.com" + aWFIS.getIconURL());
		((SingleWeatherInfoView) findViewById(aResourceID)).setRemoteImage(imgURL);

		int tempMin = aWFIS.getTempMinCelsius();
		int tempMax = aWFIS.getTempMaxCelsius();

			((SingleWeatherInfoView) findViewById(aResourceID))
					.setTempCelciusMinMax(tempMin, tempMax);
	}
	
	/**
	 * 更新天气
	 * @param 系统资源ID
	 * @param 天气状态
	 * @throws 抛出MalformedURLException异常
	 */
	private void updateWeatherInfoView(int aResourceID,
			WeatherCurrentCondition aWCIS) throws MalformedURLException {
		
		URL imgURL = new URL("http://www.google.com" + aWCIS.getIconURL());
		((SingleWeatherInfoView) findViewById(aResourceID)).setRemoteImage(imgURL);

			((SingleWeatherInfoView) findViewById(aResourceID))
					.setTempCelcius(aWCIS.getTempCelcius());
	}
	
	/**
	 * 重新设置天气预报图像
	 */
	private void resetWeatherInfoViews() {
		((SingleWeatherInfoView)findViewById(R.id.weather_today)).reset();
		((SingleWeatherInfoView)findViewById(R.id.weather_1)).reset();
		((SingleWeatherInfoView)findViewById(R.id.weather_2)).reset();
		((SingleWeatherInfoView)findViewById(R.id.weather_3)).reset();
		((SingleWeatherInfoView)findViewById(R.id.weather_4)).reset();
	}
	
	/**
	 * 判断是否中文数字
	 * @param 输入的字符串
	 * @return boolean
	 */
	public static boolean isCN(String str)
	 {
	  char chr = str.charAt(0);
	  if((chr >='a' && chr <='z') ||(chr >='A' && chr <='Z') )
	  {
	   return false;
	  }else{
	   return true;
	  }
	 }

    /**
     * 根据输入的中文字符串来判断英文字符串所在的文字
     * @param 中文数字
     * @param 输入的字符串
     * @return int
     */
	 public static int getCnPosition(String[] str_arr, String str_)
	 {
	  int result = -1;
	  for(int i = 0; i < str_arr.length; i++)
	  {
	   if(str_arr[i].equals(str_))
	   {
	    result = i;
	   }
	  }
	  return result;
	 }
	 
	 
	 /**
	  * 顶部导航ini
	  * 抽象顶部导航UI，可以脱离天气预报系统
	  */
	 private void initUI(){
			layout = (RelativeLayout) findViewById(R.id.root);
			
			layout1 = (RelativeLayout) findViewById(R.id.layout1);
			layout2 = (RelativeLayout) findViewById(R.id.layout2);
			layout3 = (RelativeLayout) findViewById(R.id.layout3);
			
			tab1 = (ImageView) findViewById(R.id.tab1);
			tab1.setOnClickListener(onClickListener);
			tab2 = (ImageView) findViewById(R.id.tab2);
			tab2.setOnClickListener(onClickListener);
			tab3 = (ImageView) findViewById(R.id.tab3);
			tab3.setOnClickListener(onClickListener);
			
			RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			rl.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
			first = new ImageView(this);
			first.setTag("first");
			first.setImageResource(R.drawable.topbar_select);
			
			// 默认选中项
			switch (current) {
			case 1:
				layout1.addView(first, rl);
				current = R.id.tab1;
				break;
			case 2:
				layout2.addView(first, rl);
				current = R.id.tab2;
				break;
			case 3:
				layout3.addView(first, rl);
				current = R.id.tab3;
				break;
			default:
				break;
			}
			
		}

		private boolean isAdd = false; // 是否添加过 top_select
		private int select_width; // top_select_width
		private int select_height; // top_select_height
		private int firstLeft; // 第一次添加后的左边距*****
		private int startLeft; // 起始左边距
		
		// 添加一个view，移除一个view
		private void replace() {
			switch (current) {
			case R.id.tab1:
				changeTop(layout1);
				break;
			case R.id.tab2:
				changeTop(layout2);
				break;
			case R.id.tab3:
				changeTop(layout3);
				break;
			default:
				break;
			}
		}
		
		private void changeTop(RelativeLayout relativeLayout){
			ImageView old = (ImageView) relativeLayout.findViewWithTag("first");;
			select_width = old.getWidth();
			select_height = old.getHeight();
			
			RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(select_width, select_height);
			rl.leftMargin = old.getLeft() + ((RelativeLayout)old.getParent()).getLeft();
			rl.topMargin = old.getTop() + ((RelativeLayout)old.getParent()).getTop();
			
			// 获取起始位置
			firstLeft = old.getLeft() + ((RelativeLayout)old.getParent()).getLeft();
			
			ImageView iv = new ImageView(this);
			iv.setTag("move");
			iv.setImageResource(R.drawable.topbar_select);
			
			layout.addView(iv , rl);
			relativeLayout.removeView(old);
		}
		
		private OnClickListener onClickListener = new OnClickListener(){
			public void onClick(View v) {
				if(!isAdd){
					replace(); // 初次使用移除old 添加新的top_select为RelativeLayout所使用
					isAdd = true;
				}
				
				ImageView top_select = (ImageView) layout.findViewWithTag("move");
				int tabLeft;
				int endLeft = 0;
				
				boolean run = false;

				switch (v.getId()) {
				case R.id.tab1:
					if (current != R.id.tab1) {
						// 中心位置
						tabLeft = ((RelativeLayout) tab1.getParent()).getLeft() + tab1.getLeft() + tab1.getWidth() / 2;
						// 最终位置
						endLeft = tabLeft - select_width / 2;
						current = R.id.tab1;
						run = true;
						
						tab1();
					}
					break;
				case R.id.tab2:
					if (current != R.id.tab2) {
						tabLeft = ((RelativeLayout) tab2.getParent()).getLeft() + tab2.getLeft() + tab2.getWidth() / 2;
						endLeft = tabLeft - select_width / 2;
						current = R.id.tab2;
						run = true;
						
						tab2();
					}
					break;
				case R.id.tab3:
					if (current != R.id.tab3) {
						tabLeft = ((RelativeLayout) tab3.getParent()).getLeft() + tab3.getLeft() + tab3.getWidth() / 2;
						endLeft = tabLeft - select_width/2;
						current = R.id.tab3;
						run = true;
						
						tab3();
					}
					break;
				default:
					break;
				}
				
				if(run){
					TranslateAnimation animation = new TranslateAnimation(startLeft, endLeft - firstLeft, 0, 0);
					startLeft = endLeft - firstLeft; // 重新设定起始位置
					animation.setDuration(400);
					animation.setFillAfter(true);
					top_select.bringToFront();
					top_select.startAnimation(animation);
				}
				
			}

		};
		
		
		
		/**
		 * tab1 按钮提示框信息
		 */
		private void tab1(){
			new AlertDialog.Builder(this)
	         .setIcon(android.R.drawable.btn_star)
	         .setTitle("公司名：")
	          .setMessage("INC: 武汉永恒成就信息科技有限公司")
	         .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	             public void onClick(DialogInterface dialog, int whichButton) {
	             }
	         }).show();
		}
		
		

		/**
		 * tab2 按钮提示框信息
		 */
		private void tab2(){
			new AlertDialog.Builder(this)
	         .setIcon(android.R.drawable.btn_star)
	         .setTitle("联系我们：")
	          .setMessage("武汉市珞瑜路243号         电话：86-027-87415595")
	         .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	             public void onClick(DialogInterface dialog, int whichButton) {
	             }
	         }).show();
		}
		
		

		/**
		 * tab3 按钮提示框信息
		 */
		private void tab3(){
			new AlertDialog.Builder(this)
	         .setIcon(android.R.drawable.btn_star)
	         .setTitle("应用程序说明：")
	          .setMessage("手机天气预报系统V1.0版。谢谢您支持！         http://www.yhcj2009.com/")
	         .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	             public void onClick(DialogInterface dialog, int whichButton) {
	             }
	         }).show();
		}
}
